import { createSSRApp } from 'vue';
import App from './App.vue';
import pinia from '@/stores';
import { serverUrl, TOKEN_KEY, getRequest, postRequestForm } from '@/utils/request.js';
import * as log from './utils/log.js'; // 正确导入

export function createApp() {
  const app = createSSRApp(App);
  app.use(pinia);

  // 全局数据
  app.config.globalProperties.$globalData = {
    serverUrl: serverUrl,
    authorization: '',
    longitude: '113.82713',
    latitude: '22.670139',
    distance: 5,
    total: 10,
    moveReflush: 0.8,
    scale: '15',
    servicePhone: '4001638819',
    userInfo: {},
    isIphoneX: false,
    getPhones: 0,
    agreementCount: 0,
    theme: {
      themeColor: '#2185F5'
    }
  };

  // 全局方法
  app.config.globalProperties.$checkUpdateMiniApp = function () {
    const updateManager = uni.getUpdateManager();
    updateManager.onCheckForUpdate((res) => {
      log.info('是否需要更新：' + res.hasUpdate);
    });
    updateManager.onUpdateReady(() => {
      uni.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: (res) => {
          if (res.confirm) {
            updateManager.applyUpdate();
          }
        }
      });
    });
    updateManager.onUpdateFailed(() => {
      log.info('下载新版本失败');
    });
  };

  // 初始化小程序
  app.config.globalProperties.$onLaunch = function (options) {
    uni.getSystemInfo({
      success: (res) => {
        let modelmes = res.model;
        if (modelmes.includes('iPhone X') || modelmes.includes('iPhone 11') || modelmes.includes('iPhone 13')) {
          this.$globalData.isIphoneX = true;
        }
        uni.setStorageSync('modelmes', modelmes);
      }
    });
    uni.removeStorageSync('getPhones');
    this.$checkUpdateMiniApp();
    log.info('app.js onLaunch options:' + JSON.stringify(options));
  };

  // 监听小程序启动或切前台
  app.config.globalProperties.$onShow = function (options) {
    if ([1006, 1027, 1022, 1089].includes(options.scene)) {
      uni.redirectTo({
        url: '/pages/map/map'
      });
    }
    log.info('app.js onShow options:' + JSON.stringify(options));
  };

  app.config.globalProperties.$onError = function (msg) {
    log.info(msg);
  };

  // 获取用户信息
  app.config.globalProperties.$getUserInfo = function (isRent = false) {
    return new Promise((resolve, reject) => {
      getRequest(
        'shiro/wechatMini/getUserInfo',
        {},
        (res) => {
          if (!res) return;
          resolve(res.data);
        },
        isRent ? '/pages/rentRule/rentRule' : '/pages/home/home',
        true
      );
    });
  };

  // 微信统一登录
  app.config.globalProperties.$wxLogin = function (callback) {
    uni.login({
      success: (res) => {
        if (res.code) {
          getRequest('shiro/wechatMini/login', { code: res.code }, (res) => {
            if (typeof callback === 'function') callback(res.data);
          });
        } else {
          if (typeof callback === 'function') callback(res.data);
        }
      }
    });
  };

  // 绑定需要回到地图页面的按钮
  app.config.globalProperties.$homeBtnBind = function (object) {
    if (object != null) {
      object.goToIndexPage = this.goToIndexPage;
    }
  };

  // 跳到首页
  app.config.globalProperties.$goToIndexPage = function () {
    try {
      uni.reLaunch({
        url: '/pages/map/map'
      });
    } catch (e) {
      console.error(e);
    }
  };

  return {
    app
  };
}
